package com.amigo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;

public class SignUp extends Activity {

	private static String url = Constants.getBaseUrl() + "register";

	private EditText Fullname, Email, Username_signup, Age, Interests,
			Password_signup;
	private String fullname, email, username_signup, dob, interests,
			password_signup;
	boolean Success = false;

	private String Message, Token;
	private Spinner Gender;
	private String gender;
	String gender_temp;
	private String array_gender[];
	private String DB_USER;
	String FBuser_id , FBuser_name ,FBuser_email;
	
	ProgressDialog ringProgressDialog =null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_sign_up);

		
	
		array_gender = new String[3];
		array_gender[0] = "Please Select Your Gender";
		array_gender[1] = "Male";
		array_gender[2] = "Female";

		Fullname = (EditText) findViewById(R.id.fullname);
		Email = (EditText) findViewById(R.id.e_mail);
		Username_signup = (EditText) findViewById(R.id.username_signup);
		Password_signup = (EditText) findViewById(R.id.password_signup);
		Age = (EditText) findViewById(R.id.Age);
		Interests = (EditText) findViewById(R.id.interest_options);

		Gender = (Spinner) findViewById(R.id.Gender);
		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_spinner_item, array_gender);
		adapter.setDropDownViewResource(R.layout.custom_dropdown_list);
		Gender.setAdapter(adapter);

		Gender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				gender = parent.getItemAtPosition(pos).toString();

			}

			public void onNothingSelected(AdapterView<?> parent) {

				gender = parent.getItemAtPosition(0).toString();
			}
		});
		Intent i = getIntent();
		if (i.hasExtra("FB_USER_exists"))
		{
		i.getBooleanExtra("FB_USER_exists", false);
		Username_signup.setText(i.getStringExtra("FBuser_id"));
		Username_signup.setEnabled(false);
		Fullname.setText(i.getStringExtra("FBuser_name"));
		Fullname.setEnabled(false);
		Email.setText(i.getStringExtra("FBuser_email"));
		Email.setEnabled(false);
		if (i.getStringExtra("FBuser_gender").equals("male"))
		Gender.setSelection(1);
		else if (i.getStringExtra("FBuser_gender").equals("female"))
		Gender.setSelection(2);
		Gender.setEnabled(false);
		Password_signup.setText(Constants.Password_FB);
		Password_signup.setEnabled(false);
		}
		
		if (i.hasExtra("GPLUS_USER_exists"))
		{
		i.getBooleanExtra("GPLUS_USER_exists", false);
		Username_signup.setText(i.getStringExtra("GPlus_id"));
		Username_signup.setEnabled(false);
		Fullname.setText(i.getStringExtra("GPlus_name"));
		Fullname.setEnabled(false);
		Email.setText(i.getStringExtra("GPlus_email"));
		Email.setEnabled(false);
		Gender.setSelection(i.getIntExtra("GPlus_gender" , -1)+1);
		Gender.setEnabled(false);
		Password_signup.setText(Constants.Password_GPLUS);
		Password_signup.setEnabled(false);
		}
	}

	public void next_signup(View v) {
		fullname = Fullname.getText().toString();
		email = Email.getText().toString();
		username_signup = Username_signup.getText().toString();
		password_signup = Password_signup.getText().toString();
		dob = Age.getText().toString();
		interests = Interests.getText().toString();

		if (checkblanks() == 0) {
			new SignupTask().execute();
		}
	}

	private int checkblanks() {
		int numberoferrors = 0;
		if (fullname.isEmpty()) {
			Fullname.setError("Name Cannot be Left Blank");
			numberoferrors++;
		}
		if (email.isEmpty()) {
			Email.setError("E-mail Cannot be Left Blank");
			numberoferrors++;
		}
		if (username_signup.isEmpty()) {
			Username_signup.setError("Username Cannot be Left Blank");
			numberoferrors++;
		}
		if (dob.isEmpty()) {
			Age.setError("Dob Cannot be Left Blank");
			numberoferrors++;
		}
		if (password_signup.isEmpty()) {
			Password_signup.setError("Password Cannot be Left Blank");
			numberoferrors++;
		}
		if (gender.equals(array_gender[0].toString())) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Error");
			builder.setMessage("This Field Cannot Be Left Blank.\n\nPlease Select Your Gender");
			builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					
				}
			});

			AlertDialog alertDialog = builder.create();
			alertDialog.setIcon(R.drawable.error_icon);
			// show it
			alertDialog.show();

			numberoferrors++;
		}
		Log.d("Num_err", "" + numberoferrors);
		return numberoferrors;
	}

	public void prev(View v) {
		Intent i = new Intent(this, Login.class);
		startActivity(i);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		finish();
	}

	private class SignupTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			ringProgressDialog = ProgressDialog.show(
					SignUp.this, "Signing Up",
					"Please Wait While We Set Up Your Account", true);
			ringProgressDialog.setCancelable(false);
			

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", username_signup));
			params.add(new BasicNameValuePair("password", password_signup));
			params.add(new BasicNameValuePair("email", email));
			params.add(new BasicNameValuePair("name", fullname));
			params.add(new BasicNameValuePair("dob", dob));
			params.add(new BasicNameValuePair("gender", gender));
			params.add(new BasicNameValuePair("interests", interests));
			params.add(new BasicNameValuePair("location", ""));
			params.add(new BasicNameValuePair("about", ""));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
					params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");
					Token = jsonObj.getString("token");
					JSONObject user = jsonObj.getJSONObject("user");
					DB_USER = user.toString();

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
		if(ringProgressDialog.isShowing())
		ringProgressDialog.dismiss();

			if (Success == true) {

				JsonFileUtility
						.CreateAndSaveFile(Constants.TAG_UserGUID, Token);
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserObject,
						DB_USER);
				Intent i = new Intent(SignUp.this, CompleteProfile.class);

				startActivity(i);

			}
		}
	}
}
